<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商家名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入商家名" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商家ID" prop="name">
        <el-input v-model="queryParams.id" placeholder="请输入商家ID" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="用户ID" prop="name">
        <el-input v-model="queryParams.uid" placeholder="请输入用户ID" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="类型" prop="name">
        <el-select v-model="queryParams.source" placeholder="请选择类型">
          <el-option label="不限制" :value="null"></el-option>
          <el-option label="线上商家" :value="1"></el-option>
          <el-option label="线下商家" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="toExamine">
        <el-select v-model="queryParams.toExamine" placeholder="请选择审核状态" clearable size="small">
          <el-option label="请选择审核状态" v-for="item in toExamineOptions" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item style="display: block">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['ds:store:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['ds:store:edit']">
          审核
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['ds:store:remove']">
          删除
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ds:product:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="商家名" align="center" prop="name" />
      <el-table-column label="用户ID" align="center" prop="uid" />
      <el-table-column label="类型" align="center">
        <template slot-scope="scope">
          {{ scope.row.source === 1 ? "线上" : "线下" }}
        </template>
      </el-table-column>
      <el-table-column label="商家图片" align="center" prop="picture">
        <template slot-scope="scope">
          <img style="width: 80px; height: 80px; border: none" :src="scope.row.picture" />
        </template>
      </el-table-column>
      <el-table-column label="地址" align="center" prop="address" min-width="150" />
      <el-table-column label="审核状态" align="center" prop="toExamine">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.toExamine == 0" type="warning">未审核</el-tag>
          <el-tag v-if="scope.row.toExamine == 1" type="success">审核通过</el-tag>
          <el-tag v-if="scope.row.toExamine == 2" type="danger">拒绝通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="添加时间" align="center" prop="createTime" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上架/下架" align="center" class-name="small-padding fixed-width" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" inactive-color="#13ce66" active-color="#ff4949" :active-value="0"
            :inactive-value="1" @change="statusChecked($event, scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button v-if="scope.row.toExamine == 0" type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['ds:store:edit']">审核</el-button>
          <el-button type="danger" @click="handleDelete(scope.row)" v-hasPermi="['ds:store:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-bod :close-on-click-modal="false"
      @close="dialogClosed">
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="商家名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名" disabled />
        </el-form-item>
        <el-form-item label="商家详情">
          <editor v-model="form.details" :min-height="192" />
        </el-form-item>
        <el-form-item label="法人代表">
          <el-input v-model="form.legalPerson" placeholder="" disabled />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="form.telephone" placeholder="" disabled />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="form.address" placeholder="" disabled />
        </el-form-item>
        <el-row>
          <el-col :span="10">
            <el-form-item label="身份证正面">
              <imageUpload v-model="form.frontIdCard" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="身份证背面">
              <imageUpload v-model="form.reverseIdCard" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="营业执照">
          <imageUpload v-model="form.businessLicense" />
        </el-form-item>
        <el-row>
          <el-col :span="20">
            <el-form-item label="备注">
              <editor v-model="form.remarks" :min-height="130" />
            </el-form-item>
          </el-col>
          <el-col :span="4" style="color: red">
            (开发者寄语)
            审核人员请注意，如您拒绝通过，请再原备注另起一行，确保输入原因，再点击拒绝按钮
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="pass">通 过</el-button>
        <el-button type="danger" @click="refuse">拒 绝</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listStore,
  getStore,
  delStore,
  addStore,
  updateStore,
  exportStore,
  passStore,
  updateStatueStore
} from "@/api/ds/store";
import {
  updateProduct
} from "@/api/ds/product";
import ImageUpload from "@/components/ImageUpload";
import ImagesUpload from "@/components/ImagesUpload";
import Editor from "@/components/Editor";
import { getToken } from "@/utils/auth";

export default {
  name: "Product",
  components: {
    ImageUpload,
    ImagesUpload,
    Editor,
  },
  data() {
    var validateID = (rule, value, callback) => {
      if (value) {
        if (!/^([1-9][0-9]*){1,3}$/.test(value)) {
          callback(new Error("请输入正确的值"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入值"));
      }
    };
    var validatePrice = (rule, value, callback) => {
      if (value) {
        if (!/^([1-9][0-9]*)+(.[0-9]{1,2})?$/.test(value)) {
          callback(new Error("请输入正确的价格（最多两位小数）"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入价格"));
      }
    };
    return {
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/uploadImage", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      filesList: [],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品信息表格数据
      storeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      passFlag: true,
      refuseFlag: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        toExamine: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        image: [{ required: true, message: "商品图不能为空", trigger: "blur" }],
        sliderImage: [
          { required: true, message: "轮播图不能为空", trigger: "blur" },
        ],
        name: [{ required: true, message: "商品名不能为空", trigger: "blur" }],
        cateId: [{ required: true, validator: validateID, trigger: "blur" }],
        price: [{ required: true, message: "进价不能为空", trigger: "blur" }],
        vipPrice: [
          { required: true, message: "售价不能为空", trigger: "blur" },
        ],
        sales: [{ required: true, message: "销量不能为空", trigger: "blur" }],
        stock: [{ required: true, message: "库存不能为空", trigger: "blur" }],
        quota: [{ required: true, message: "贡献值不能为空", trigger: "blur" }],
        giftAmount: [
          { required: true, message: "赠送倍数不能为空", trigger: "blur" },
        ],
        limitNum: [
          { required: true, message: "限购数量不能为空", trigger: "blur" },
        ],
      },
      isMixPay: false, // 是否混合支付
      toExamineOptions: [
        // 分类下拉框
        {
          value: "0",
          label: "未审核",
        },
        {
          value: "1",
          label: "审核通过",
        },
        {
          value: "2",
          label: "拒绝通过",
        },
      ],
    };
  },
  created() {
    this.getList();
  },

  methods: {
    /** 查询商品信息列表 */
    getList() {
      this.loading = true;

      listStore(this.queryParams).then((response) => {
        this.storeList = response.rows;
        console.log(this.storeList);
        this.total = response.total;
        this.loading = false;
      });
    },
    dialogClosed() {
      this.open = false;
      this.$refs.upload.clearFiles(); // 取消按钮也要清一遍轮播图
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    // 操作上下架switch按钮
    statusChecked(e, row) {
      row.status = e;
      let query={
        id:row.id,
        status:row.status
      }
      updateStatueStore(query).then((response) => {
        this.msgSuccess("修改成功");
        this.getList();
      });
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isMixPay = false;
      this.open = true;
      this.title = "添加商家信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getStore(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "审核商家";
      });
    },
    /** 通过 */
    pass() {
      if (this.passFlag) {
        this.passFlag = false
        this.form.toExamine = 1;
        passStore(this.form).then((res) => {
          if (res.code == 200) {
            this.open = false;
            this.msgSuccess("审核通过");
            this.passFlag = true
          }
          this.getList();
        });
      }
    },
    /** 拒绝*/
    refuse() {
      if (this.refuseFlag) {
        this.refuseFlag = false
        this.form.toExamine = 2;
        passStore(this.form).then((res) => {
          if (res.code == 200) {
            this.open = false;
            this.msgError("拒绝通过");
            this.refusekFlag = true
          }
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除商品信息编号为"' + ids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delProduct(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有商品信息数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportProduct(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    /** 当关闭混合支付按钮时，gtfy支付比例归0 */
    payTypeChanged() {
      if (!this.isMixPay) {
        this.form.passProportion = 0;
        this.form.cashRatio = 100;
      }
    },
  },
};
</script>
<style>
.actualPay {
  width: 33%;
  text-align: center;
  margin-left: 6%;
  display: inline-block;
  color: white;
  background: #1890ff;
  font-weight: 600;
  border-radius: 4px;
}
</style>
